package com.lz.yz.order.service.impl;

import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.util.Constant;
import com.lz.yz.core.AbstractService;
import com.lz.yz.empowerment.Param.ShareOrderCount;
import com.lz.yz.empowerment.Param.ShareOrderParam;
import com.lz.yz.empowerment.dao.QuestionBuffMapper;
import com.lz.yz.empowerment.dao.QuestionShareMapper;
import com.lz.yz.empowerment.entity.QuestionBuff;
import com.lz.yz.empowerment.entity.QuestionShare;
import com.lz.yz.member.dao.PropertyInfoMapper;
import com.lz.yz.member.entity.PropertyInfo;
import com.lz.yz.member.service.PropertyInfoService;
import com.lz.yz.order.dao.OrdersMapper;
import com.lz.yz.order.entity.Orders;
import com.lz.yz.order.enumeration.OrderStatus;
import com.lz.yz.order.enumeration.OrderType;
import com.lz.yz.order.enumeration.TurnoversType;
import com.lz.yz.order.model.OrderModel;
import com.lz.yz.order.service.OrdersService;
import com.lz.yz.order.service.TurnoversService;
import com.lz.yz.outing.service.CreateNo;
import com.lz.yz.outing.service.SyncLockService;
import com.lz.yz.reward.entity.Reward;
import com.lz.yz.reward.service.RewardService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
@Transactional
public class OrdersServiceImpl extends AbstractService<Orders> implements OrdersService {
    @Resource
    private OrdersMapper ordersMapper;

    @Autowired
    SyncLockService syncLockService;

    @Autowired
    CreateNo createNo;

    @Autowired
    TurnoversService turnoversService;

    @Autowired
    QuestionBuffMapper questionBuffMapper;

    @Autowired
    QuestionShareMapper questionShareMapper;

    @Autowired
    RewardService rewardService;

    @Autowired
    PropertyInfoMapper propertyInfoMapper;

    @Autowired
    PropertyInfoService propertyInfoService;


    @Override
    public ReturnValue add(Integer accountId, OrderModel orderModel) {
        if(orderModel.getOrderType()==null){
            return ReturnValue.generateFalseReturnValue("订单类型不能为空!");
        }
        //控制双重点击事件
        if (!syncLockService.syncLock("addOrder/" + orderModel.getOrderType() + "/" + accountId, 5, TimeUnit.SECONDS)) {
            return ReturnValue.generateFalseReturnValue("请不要重复提交!");
        }
        Orders order = new Orders();
        QuestionBuff questionBuff=new QuestionBuff();
        OrderType orderType= OrderType.getOrderTypeByIndex(orderModel.getOrderType());
        switch (orderType){
            case REWARD: //找大咖订单
                BeanUtils.copyProperties(orderModel,order);
                order.setOrderNo(createNo.getNo(accountId,orderModel.getOrderType()+""));
                order.setBuyerAccountId(accountId);
                order.setStatus(OrderStatus.SERVICE.getStatusValue());
                break;
            case QUESTIONBUFF://赋能
                Orders order2 = new Orders();
                order2.setOrderType(OrderType.QUESTIONBUFF.getStatusValue());
                order2.setObjectiveId(orderModel.getObjectiveId());
                order2.setBuyerAccountId(accountId);
                order2.setStatus(OrderStatus.COMPLETE.getStatusValue());
                order2=ordersMapper.selectOne(order2);
                if(null!=order2){
                    return ReturnValue.generateFalseReturnValue("该用户已参与过赋能");
                }

                PropertyInfo propertyInfo=new PropertyInfo();
                propertyInfo.setAccountId(accountId);
                propertyInfo= propertyInfoMapper.selectOne(propertyInfo);
                BigDecimal integral = new BigDecimal(propertyInfo.getIntegral()); //资产积分
                BigDecimal proportion = new BigDecimal( 10);//比率
                BigDecimal intBalance=integral.divide(proportion);
               if(orderModel.getBackParams().equals("1")){
                   if(intBalance.compareTo(orderModel.getTotalPrice())==0){ // 积分与赋能价格一致
                       BigDecimal balanceClear= new BigDecimal( 0);
                       BigDecimal  consumptionIntegral=orderModel.getTotalPrice().multiply(proportion);
                       order.setTotalPrice(balanceClear);
                       order.setDiscountIntegral(consumptionIntegral.intValue());
                   }
                   if(intBalance.compareTo(orderModel.getTotalPrice())==1){  // 积分大于赋能价格
                       BigDecimal  consumptionIntegral=orderModel.getTotalPrice().multiply(proportion);
                       BigDecimal balanceClear= new BigDecimal( 0);
                       order.setTotalPrice(balanceClear);
                       order.setDiscountIntegral(consumptionIntegral.intValue());
                   }

                   if(intBalance.compareTo(orderModel.getTotalPrice())==-1){// 积分小于赋能价格
                       BigDecimal  consumptionIntegral=orderModel.getTotalPrice().multiply(proportion);
                       order.setTotalPrice(orderModel.getTotalPrice().subtract(intBalance));
                       order.setDiscountIntegral(integral.intValue());
                   }
               }else{
                   order.setTotalPrice(orderModel.getTotalPrice());
                   BigDecimal balanceClear1= new BigDecimal( 0);
                   order.setDiscountIntegral(balanceClear1.intValue());
               }


                questionBuff.setId(orderModel.getObjectiveId());
                questionBuff=questionBuffMapper.selectOne(questionBuff);
               // BeanUtils.copyProperties(orderModel,order);
                order.setOrderType(orderModel.getOrderType());
                order.setObjectiveId(orderModel.getObjectiveId());
                order.setOrderNo(createNo.getNo(accountId,orderModel.getOrderType()+""));
                order.setBuyerAccountId(accountId);
                order.setSellersAccountId(questionBuff.getAccountId());
                order.setStatus(OrderStatus.SERVICE.getStatusValue());
                break;
            case FLAT://平摊
                QuestionShare questionShare=new QuestionShare();
                questionShare.setId(orderModel.getObjectiveId());
                questionShare=questionShareMapper.selectOne(questionShare);
                if(null!=questionShare){
                    if(questionShare.getaCount()<=1){
                        return ReturnValue.generateFalseReturnValue("平摊不可少于1人");
                    }
                    ShareOrderParam shareOrderParam=new ShareOrderParam();
                    shareOrderParam.setShareId(orderModel.getObjectiveId());
                    shareOrderParam.setShareUserId(questionShare.getAccountId());
                    ShareOrderCount shareOrderCount=questionBuffMapper.queryShareOrderNumByPay(shareOrderParam);
                        if(questionShare.getStatus()!=2){
                                    //平摊更改
                                    BigDecimal number  = new BigDecimal(questionShare.getaCount());
                                    BigDecimal danjia=questionShare.getaPrice().divide(number,1, BigDecimal.ROUND_HALF_EVEN);
                                    if(null!=orderModel.getIsExcess()){
                                        if(shareOrderCount.getOrderNum()==0){
                                            order.setTotalPrice(questionShare.getaPrice());
                                        }else{
                                            order.setTotalPrice(questionShare.getaPrice().subtract(shareOrderCount.getTotalPrice()));
                                        }
                                    }else{
                                        order.setTotalPrice(danjia);
                                    }
                                    order.setOrderNo(createNo.getNo(accountId, orderModel.getOrderType() + ""));
                                    order.setBuyerAccountId(accountId);
                                    questionBuff.setId(questionShare.getQuestionId());
                                    questionBuff = questionBuffMapper.selectOne(questionBuff);
                                    order.setObjectiveId(orderModel.getObjectiveId());
                                    order.setOrderType(orderModel.getOrderType());
                                    order.setShareQuestionId(questionBuff.getId());
                                    order.setSellersAccountId(questionBuff.getAccountId());
                                    order.setStatus(OrderStatus.SERVICE.getStatusValue());


                        }else{
                            return ReturnValue.generateFalseReturnValue("该平摊活动已完成，不可下单");
                        }



                }


                break;
            case GET: //GET订单
                BeanUtils.copyProperties(orderModel,order);
                order.setOrderNo(createNo.getNo(accountId,orderModel.getOrderType()+""));
                order.setBuyerAccountId(accountId);
                order.setStatus(OrderStatus.SERVICE.getStatusValue());
                break;
        }
        ordersMapper.insertSelective(order);
        return ReturnValue.generateTrueReturnValue(order.getOrderNo());
    }

    @Override
    public Boolean orderNotify(Orders order, String backParams) {
        String outTradeNo=order.getOrderNo();
        OrderType orderType=OrderType.getOrderTypeByIndex(order.getOrderType());
        BigDecimal totalPrice = order.getTotalPrice();
        switch (orderType){
            case REWARD: //找大咖订单
                //修改订单支付状态
                order.setStatus(OrderStatus.COMPLETE.getStatusValue());
                order.setPayDate(new Date());
                order.setCompletedAt(new Date());
                if(ordersMapper.updateByPrimaryKeySelective(order)==0){
                    return false;
                }
                //绑定悬赏中订单号
                rewardService.update(new Reward(order.getObjectiveId(),outTradeNo));

                //针对资产表的流水变动
                turnoversService.insert(order.getBuyerAccountId(), TurnoversType.REWARD, Constant.SUBTRACTION,totalPrice,outTradeNo);
                break;
            case QUESTIONBUFF: //赋能订单
                //修改订单支付状态
                order.setStatus(OrderStatus.COMPLETE.getStatusValue());
                order.setPayDate(new Date());
                order.setCompletedAt(new Date());
                if(ordersMapper.updateByPrimaryKeySelective(order)==0){
                    return false;
                }
             if(backParams.equals("1")){
                 BigDecimal orderIntegral = new BigDecimal(order.getDiscountIntegral());
                 propertyInfoService.decreaseIntegral(order.getBuyerAccountId(),orderIntegral);
                 propertyInfoService.increaseIntegral(order.getSellersAccountId(),orderIntegral);
                 propertyInfoService.increaseBalance(order.getSellersAccountId(),order.getTotalPrice());
                 turnoversService.insert(order.getBuyerAccountId(), TurnoversType.INTEGRAL, Constant.SUBTRACTION,orderIntegral,outTradeNo);
                 turnoversService.insert(order.getSellersAccountId(), TurnoversType.INTEGRAL, Constant.ADDITION,orderIntegral,outTradeNo);
                 turnoversService.insert(order.getBuyerAccountId(), TurnoversType.QUESTIONBUFF, Constant.SUBTRACTION,order.getTotalPrice(),outTradeNo);
                 turnoversService.insert(order.getSellersAccountId(), TurnoversType.QUESTIONBUFF, Constant.ADDITION,order.getTotalPrice(),outTradeNo);
                }else{
                 /*propertyInfoService.decreaseBalance(order.getBuyerAccountId(),order.getTotalPrice());*/
                 propertyInfoService.increaseBalance(order.getSellersAccountId(),order.getTotalPrice());
                 turnoversService.insert(order.getBuyerAccountId(), TurnoversType.QUESTIONBUFF, Constant.SUBTRACTION,order.getTotalPrice(),outTradeNo);
                 turnoversService.insert(order.getSellersAccountId(), TurnoversType.QUESTIONBUFF, Constant.ADDITION,order.getTotalPrice(),outTradeNo);
                }
                break;
            case FLAT: //平摊订单
                QuestionShare questionShare=new QuestionShare();
                questionShare.setId(order.getObjectiveId());
                questionShare=questionShareMapper.selectOne(questionShare);
                if(null!=questionShare){
                    ShareOrderParam shareOrderParam=new ShareOrderParam();
                    shareOrderParam.setShareId(order.getObjectiveId());
                    ShareOrderCount shareOrderCount=questionBuffMapper.queryShareOrderNumByPay(shareOrderParam);
                    Boolean falg=false;

                   if(questionShare.getStatus()==1){
                             if(shareOrderCount.getTotalPrice()==null){
                                 BigDecimal priceClear= new BigDecimal( 0);
                                 shareOrderCount.setTotalPrice(priceClear);
                             }
                            falg=shareOrderCount.getTotalPrice().add(order.getTotalPrice()).compareTo(questionShare.getaPrice())==0;
                           if(shareOrderCount.getOrderNum().equals(questionShare.getaCount()-1)||falg){
                               questionShare.setStatus(2);
                               questionShareMapper.updateByPrimaryKeySelective(questionShare);
                               int ret = propertyInfoService.increaseBalance(order.getSellersAccountId(),questionShare.getaPrice());
                               //针对卖家资产表的流水变动
                               turnoversService.insert(order.getSellersAccountId(), TurnoversType.FLAT, Constant.ADDITION, questionShare.getaPrice(), outTradeNo);
                            }

                       //修改平摊订单支付状态
                       order.setStatus(OrderStatus.COMPLETE.getStatusValue());
                       order.setPayDate(new Date());
                       order.setCompletedAt(new Date());
                       if(ordersMapper.updateByPrimaryKeySelective(order)==0){
                           return false;
                       }
                       //针对买家资产表的流水变动
                       turnoversService.insert(order.getBuyerAccountId(), TurnoversType.FLAT, Constant.SUBTRACTION, totalPrice, outTradeNo);
                   }else{
                       return false;
                   }
                }
                break;
            case GET: //GET订单
                //修改订单支付状态
                order.setStatus(OrderStatus.COMPLETE.getStatusValue());
                order.setPayDate(new Date());
                order.setCompletedAt(new Date());
                if(ordersMapper.updateByPrimaryKeySelective(order)==0){
                    return false;
                }
                //针对资产表的流水变动
                turnoversService.insert(order.getBuyerAccountId(), TurnoversType.GET, Constant.SUBTRACTION,totalPrice,outTradeNo);
                break;
        }
        return true;
    }
}
